package mongodb

// 创建 MongoDB 连接

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/fx"
	"go.uber.org/zap"
)

type MongoDBConfig struct {
	URI      string
	Database string
}

func NewMongoDBConfig() *MongoDBConfig {
	return &MongoDBConfig{
		URI:      "mongodb://root:Zmzzmz010627!@localhost:27017/?authSource=admin",
		Database: "efficientTest",
	}
}

func NewMongoDBStore(lc fx.Lifecycle, conf *MongoDBConfig, logger *zap.Logger) (*mongo.Database, error) {
	logger.Info("Connecting to MongoDB", zap.String("URI", conf.URI), zap.String("database", conf.Database))

	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(conf.URI))
	if err != nil {
		logger.Error("Failed to connect to MongoDB", zap.Error(err))
		return nil, err
	}

	lc.Append(fx.Hook{
		OnStop: func(ctx context.Context) error {
			return client.Disconnect(ctx)
		},
	})

	err = client.Ping(context.Background(), nil)
	if err != nil {
		logger.Error("Failed to ping MongoDB", zap.Error(err))
		return nil, err
	}

	mongoDatabase := client.Database(conf.Database)
	return mongoDatabase, nil
}
